import Axios from 'axios';
import { message } from 'antd';
import config from "../config/config";

Axios.defaults.timeout = 6000000;
Axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

export function get(url, data, isAuth = true) {
  if (url) {
    url = createRequestUrl(url, data);

    const instance = Axios.create();
    instance.interceptors.request.use(config => {
      if (isAuth) {
        config.headers["Authorization"] = window._TOKEN_ || sessionStorage.getItem("token");
      }
      config.timeout = 6000000;
      return config;
    });

    let response = new Promise((resolve, reject) => {
      instance.get(url).then(res => {
        return resolve(res.data);
      }).catch(error => {
        if (error.response) {
          const status = error.response?.status;
          if (status == "400" || status == "404") {
            message.error("客户端请求错误！");
          } else if (status == "500") {
            message.error("服务器内部错误！");
          }
        } else {
          message.error("请求失败！");
        }
        console.log("Get Request " + error);
        return reject(error);
      });
    });
    return response;
  } else {
    console.log("Get Request Params:  [url] ===> " + url + " [data] ===> " + data);
    message.error("请求格式不正确！");
    return null;
  }
}

export function post(url, data, responseType = "json") {
  if (url && data) {
    const params = {
      method: "post",
      url: url,
      data: data,
      responseType: responseType
    };

    const instance = Axios.create();
    instance.interceptors.request.use(config => {
      config.headers["Authorization"] = window._TOKEN_ || "";
      config.timeout = 6000000;
      return config;
    });

    let response = new Promise((resolve, reject) => {
      instance.request(params).catch(error => {
        console.log("post request error: ", error);
        return reject(error);
      }).then(res => {
        return resolve(res.data);
      }).catch(error => {
        const status = error.response?.status;
        if (status == "400" || status == "404") {
          message.error("客户端请求错误！");
        } else if (status == "500") {
          message.error("服务器内部错误！");
        }
        console.log("Post Request " + error);
        return reject(error);
      })
    });
    return response;
  } else {
    console.log("Post Request Params:  [url] ===> " + url + " [data] ===> " + data);
    message.error("请求格式不正确！");
    return null;
  }
}

export function upload(url, params) {
  try {
    const formData = new FormData();
    formData.append('file', params.file);
    const requestObj = {
      method: "post",
      url: url,
      data: formData,
      header: {
        "Content-Type": "multipart/form-data"
      }
    }

    let response = new Promise((resolve, reject) => {
      Axios.defaults.timeout = 6000000;
      Axios.create().request(requestObj).then(res => {
        console.log("Upload Request res => ", res);
        return resolve(res.data);
      }).catch(error => {
        console.log("Upload Request Error: " + error);
        return reject(error);
      });
    });
    return response;
  } catch (e) {
    console.log("Upload Request error: ", e);
    return null;
  }
}

export function downlaod(url, data, responseType = "blob") {
  if (url && data) {
    const params = {
      method: "post",
      url: url,
      data: data,
      responseType: responseType
    };

    const instance = Axios.create();
    instance.interceptors.request.use(config => {
      config.headers["Authorization"] = window._TOKEN_ || "";
      config.timeout = 6000000;
      return config;
    });

    let response = new Promise((resolve, reject) => {
      instance.request(params).catch(error => {
        console.log("post request error: ", error);
        return reject(error);
      }).then(res => {
        return resolve(res.data);
      }).catch(error => {
        const status = error.response?.status;
        if (status == "400" || status == "404") {
          message.error("客户端请求错误！");
        } else if (status == "500") {
          message.error("服务器内部错误！");
        }
        console.log("Post Request " + error);
        return reject(error);
      })
    });
    return response;
  } else {
    console.log("Post Request Params:  [url] ===> " + url + " [data] ===> " + data);
    message.error("请求格式不正确！");
    return null;
  }
}

function createRequestUrl(url, data) {
  let getUrl = "";
  if (data) {
    Object.keys(data).forEach((item) => {
      if (data[item]) {
        getUrl += item + "=" + data[item] + "&";
      }
    });
  } else {
    getUrl = url;
  }
  if (getUrl.indexOf("&") > 0) {
    url = url + "?" + getUrl.substr(0, getUrl.length - 1);
  }
  return url;
}
